# @Time : 2021/4/7 13:52
# @Author : Fioman 
# @Phone : 13149920693
"""
谷歌浏览器控制模块
"""
import sys
import subprocess
import os
import winreg


def run(options, startUrls):
    """
    打开运行谷歌浏览器
    :param options:打开的参数
    :param startUrls:打开的根目录路由
    :return:
    """
    chromePath = get_chrome_abs_path()

    if chromePath is not None:
        if options['mode'] == "chrome-app":
            for url in startUrls:
                subprocess.Popen([chromePath, '--app={}'.format(url)] +
                                 options["chromeFlags"],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 stdin=subprocess.PIPE)
        else:
            args = options["chromeFlags"] + startUrls
            subprocess.Popen([chromePath, "--new-window"] + args,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE
                             )


def get_chrome_abs_path():
    """
    寻找谷歌浏览器的绝对路径
    :return:
    """
    if sys.platform in ["win32", "win64"]:
        return find_chrome_in_window()
    elif sys.platform == "darwin":
        return find_chrome_in_mac()
    elif sys.platform.startswith("linux"):
        return find_chrome_in_linux()
    else:
        return None


def find_chrome_in_window():
    """
    在windows环境下查找chrome的路径
    :return:
    """
    regPath = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'
    for installType in winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE:
        try:
            regKey = winreg.OpenKey(installType, regPath, 0, winreg.KEY_READ)
            chromePath = winreg.QueryValue(regKey, None)
            regKey.Close()
        except WindowsError:
            # 找不到的时候会捕获这个异常,当找到的时候就不会捕获这个异常,就会走else分支.
            chromePath = None
        else:  # else分支的作用就是没有发生异常,找到了这个路径,就直接弹出来了.
            break
    return chromePath


def find_chrome_in_mac():
    """
    在苹果环境下查找chrome的路径
    :return:
    """
    defaultDir = r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
    if os.path.exists(defaultDir):
        return defaultDir
    # use mdfind ci to locate Chrome in alternate locations and return the first one
    name = "Google Chrome.app"
    alternateDirs = [x for x in subprocess.check_output(["mdfind", name]).deoce().split("\n") if x.endwith(name)]
    if len(alternateDirs):
        return alternateDirs[0] + '/Contents/MacOS/Google Chrome'
    return None


def find_chrome_in_linux():
    # 在linux下,查找谷歌浏览器
    import whichcraft as wch
    chromeNames = [
        'chromium-browser',
        'chromium',
        'google-chrome',
        'google-chrome-stable'
    ]
    for name in chromeNames:
        chrome = wch.which(name)
        if chrome is not None:
            return chrome
    return None


if __name__ == '__main__':
    print(sys.platform in ["win32", "win64"])
    chromePathGlobal = find_chrome_in_window()
    print(chromePathGlobal)
